package com.base.component.app.apple;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Locale;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.gitee.magic.core.json.JsonArray;
import com.gitee.magic.core.json.JsonObject;
import com.gitee.magic.framework.head.utils.IoUtils;

/**
 * https://www.cnblogs.com/lazydays/p/12078006.html
 * @author zywei
 *
 */
public class IapService {

	private static class TrustAnyTrustManager implements X509TrustManager {

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}

	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

	public static final String url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
	public static final String url_verify = "https://buy.itunes.apple.com/verifyReceipt";

	public static String buyAppVerify(String receipt) throws Exception {
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
		URL console = new URL(url_sandbox);
		HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
		conn.setSSLSocketFactory(sc.getSocketFactory());
		conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/json");
		conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
		conn.setDoInput(true);
		conn.setDoOutput(true);
		BufferedOutputStream hurlBufOus = new BufferedOutputStream(conn.getOutputStream());
		String str = String.format(Locale.CHINA, "{\"receipt-data\":\"" + receipt + "\"}");// 拼成固定的格式传给平台
		hurlBufOus.write(str.getBytes());
		hurlBufOus.flush();
		InputStream is = conn.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String line = null;
		StringBuffer sb = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			sb.append(line);
		}
		return sb.toString();
	}

	public void iPayNotify(String productId, String receipt, String orderNo) throws Exception {
		// 1.先线上测试 发送平台验证
		String verifyResult = IapService.buyAppVerify(receipt);
		System.out.println(verifyResult);
		JsonObject job = new JsonObject(verifyResult);
		String states = job.getString("status");
		// 前端所提供的收据是有效的 验证成功
		if (!states.equals("0")) {
			return;
		}
		String r_receipt = job.getString("receipt");
		JsonObject returnJson = new JsonObject(r_receipt);
		String in_app = returnJson.getString("in_app");
		JsonArray jsonArray = new JsonArray(in_app);
		for (int i = 0; i < jsonArray.length(); i++) {
			JsonObject productJson=jsonArray.getJsonObject(i);
			String prodId=productJson.getString("product_id") ;
			if (productId.equals(prodId)) {
				String transaction_id = productJson.getString("transaction_id");
				System.out.println(transaction_id);
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		String receipt=IoUtils.getFileStringContent("/Users/mac/Desktop/有订阅.json");
		IapService i=new IapService();
		i.iPayNotify(null,receipt,null);
	}

}
